<?php

/**
This script handles the log-in feature of the site.
*/

include("login_constants.php");
//include("write_functions.php");

/**
Calls on the displayLoggedInBox function at loggedinbox.js to generate the
black bar's contents when a user is logged in.
*/
function showLoggedInBox(){
	global $dots;
	echo_js($dots . "boilerplate/js/loggedinbox.js");
	echo "<script type='text/javascript' language='javascript'>\n";
	echo "displayLoggedInBox('" . $_SESSION['username'] . "')\n";
	echo "</script>";
}

// Try to get the $_POST variables associated with logging-in.
$username = $_POST["username"];
$password = $_POST["password"];

// User entered something in the login form. Hence, the log-in
// $_POST variables are not null.
if($username != Null and $password != Null){
	connect("","","","");
	
	$username = mysql_real_escape_string($username);
	$password = mysql_real_escape_string(sha1($password));

	// Query the database for the given username and password.
	$account_query = sprintf("SELECT * FROM account WHERE username = '%s' AND password = '%s'",
							 $username,
							 $password);
	
	$account_resource = mysql_query($account_query);
	$account = mysql_fetch_array($account_resource);
	
	// Username and password matched. Set the $_SESSION variables
	// and display the logged-in box. Also, check if account is a student.
	if($account){
		
		$_SESSION["username"] = $username;
		$_SESSION["logged_in"] = True;
		$_SESSION["student"] = $account["type"] == "S";
		
		showLoggedInBox();
		
	} else{ // Username and password unrecognized
		$_SESSION["login_failure"] = True;
		echo "<script type='text/javascript' language='javascript'>window.history.back()</script>";
	}
	
} else{ // User didn't input anything.
	if($_SESSION["logged_in"]){
		showLoggedInBox();
	} else{
		echo_js($dots . "boilerplate/js/loginbox.js");
	}
}
?>